package me.boot.web.common.template.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import lombok.Getter;
import lombok.Setter;
import me.base.utils.ReflectUtil;
import me.boot.db.mybatis.template.entity.AutoEntity;
import me.boot.db.mybatis.utils.MpUtils;

@Getter
@Setter
public abstract class BaseLinkEntity<L extends AutoEntity, R extends AutoEntity>
        extends AutoEntity implements LinkEntity<L, R> {

    @TableField(exist = false)
    protected Class<L> lClass;

    @TableField(exist = false)
    protected Class<R> rClass;

    protected abstract Long getLeftId();

    protected abstract Long getRightId();

    @Override
    public L getLeft() {
        return getMapper(getLClass()).selectById(getLeftId());
    }

    @Override
    public R getRight() {
        return getMapper(getRClass()).selectById(getRightId());
    }

    protected <E> BaseMapper<E> getMapper(Class<E> clazz) {
        return MpUtils.getMapper(clazz);
    }

    protected Class<L> getLClass() {
        if (lClass == null) {
            this.lClass = ReflectUtil.getGenericType(this.getClass(), 0);
        }
        return lClass;
    }

    protected Class<R> getRClass() {
        if (rClass == null) {
            this.rClass = ReflectUtil.getGenericType(this.getClass(), 1);
        }
        return rClass;
    }
}
